package com.beiye.drivertransport.thematic.learning.finishedfragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.frame.adapter.CommonAdapter;
import com.android.frame.adapter.ViewHolder;
import com.android.frame.http.HttpListener;
import com.android.frame.view.linearlistview.LinearListView;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.SignExaminationthematiclearningActivity;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.CheckExamtimeBean;
import com.beiye.drivertransport.bean.DaiKaoCourseBean;
import com.beiye.drivertransport.bean.DaikaoBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.MineUseBean;
import com.beiye.drivertransport.bean.PayMentSencondBean;
import com.beiye.drivertransport.bean.SpecifiedLearnAllBean;
import com.beiye.drivertransport.bean.ThematicLearnRecordBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.fragment.TwoBaseFgt;
import com.beiye.drivertransport.header.WindmillHeader;
import com.beiye.drivertransport.http.Course;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.thematic.learning.AdministratorInformationcompletionActivity;
import com.beiye.drivertransport.thematic.learning.NewPaymentActivity;
import com.beiye.drivertransport.thematic.learning.examiantion.AdministratorcertificateActivity;
import com.beiye.drivertransport.thematic.learning.examiantion.CertificateCompletionActivity;
import com.beiye.drivertransport.thematic.learning.examiantion.ContinuingEducationActivity;
import com.beiye.drivertransport.thematic.learning.examiantion.ExaminationthematiclearningActivity;
import com.beiye.drivertransport.thematic.learning.examiantion.HaveExaminationthematiclearningActivity;
import com.beiye.drivertransport.thematic.learning.examiantion.InitialposttrainingActivity;
import com.beiye.drivertransport.utils.Constants;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.SharePerferenceUtils;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;


import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
//考试
public class ExaminationthematiclearnedFragment extends TwoBaseFgt {

    PtrClassicFrameLayout ptr_main;//下拉刷新

    TextView tv_exam_learning;

    TextView tv_exam3;//验证学习

    RelativeLayout re_test;//学习记录

    TextView tv_exam4;//验证身份证

    TextView tv_test3;


    LinearListView lv_exam;

    private ExamationAdapter examationAdapter;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    List<DaikaoBean.RowsBean> finishrows = new ArrayList<>();//已完成卷子
    List<DaikaoBean.RowsBean> finishnorows = new ArrayList<>();//未完成卷子
    List<DaikaoBean.RowsBean> finishrowslist = new ArrayList<>();//已完成及格卷子
    List<DaikaoBean.RowsBean> finishrowsfaillist = new ArrayList<>();//已完成未及格卷子
    List<DaikaoBean.RowsBean> newrows = new ArrayList<>();
    //    private PopupWindow mUserPopWindow;
//    private EditText ed_id;
//    private PopupWindow mUserihvePopWindow;
//    private EditText ed_idiver;
    private PopupWindow mPurchasePopWindow;
    private IWXAPI api;
    //下拉次数
    private int ptrTimes;
    List<SpecifiedLearnAllBean.RowsBean> jiayunbaoSpecified = new ArrayList<>();

    private static final int THEMATIC_LEARNRECORD_DATA = 5;
    private int sn;
    private int uqpSn;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_examinationthematiclearning;
    }


    @Override
    public void onClick(View view) {

    }

    //申请考卷业务方法
    public void ApplyExamtion() {
        SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
        int stId = sp.getInt("stId", 0);
        String orgId = sp.getString("orgId", "");
        String twoDecimal = sp.getString("twoDecimal", "");
        String stName = sp.getString("stName", "");
        float newrice = Float.parseFloat(twoDecimal);
        int payMark = sp.getInt("payMark", 0);
        int chargeMark = sp.getInt("chargeMark", 0);
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean databean = userInfo.getData();
        String userId = databean.getUserId();
        if (chargeMark == 1 || chargeMark == 2) {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(getContext(),
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                return;
            }
            showLoadingDialog("");
            new Login().getApplyExamtionthematiclear(userId, orgId, stId, this, 1);//申请考试
        } else if (chargeMark == 3) {
            if (payMark == 2 || payMark == 1) {//2已付费 1免费
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(getContext(),
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                    return;
                }
                showLoadingDialog("");
                new Login().getApplyExamtionthematiclear(userId, orgId, stId, this, 1);//申请考试
            } else if (payMark == 0) {//待支付
                Bundle bundle = new Bundle();
                bundle.putString("orgId", orgId);
                bundle.putInt("stId", stId);
                bundle.putInt("paytag", 3);
                bundle.putFloat("price", newrice);
                bundle.putString("stName", stName);
                bundle.putString("uqcSn", null);
                startActivity(NewPaymentActivity.class, bundle);
            }
        }
    }


    /*****
     * 接受第二个Activity返回的数据时调用
     *
     * ****/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }
//        // 根据返回码的不同，设置参数
//        if (requestCode == 0) {//继续教育补全信息后直接申请考试
//            if (resultCode == 1) {
//                //检测是否有写的权限
//                SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
//                int stId = sp.getInt("stId", 0);
//                String orgId = sp.getString("orgId", "");
//                LoginUserBean userInfo = UserManger.getUserInfo();
//                LoginUserBean.DataBean databean = userInfo.getData();
//                String userId = databean.getUserId();
//                int permission = ActivityCompat.checkSelfPermission(getContext(),
//                        "android.permission.WRITE_EXTERNAL_STORAGE");
//                if (permission != PackageManager.PERMISSION_GRANTED) {
//                    // 没有写的权限，去申请写的权限，会弹出对话框
//                    ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
//                    return;
//                }
//                showLoadingDialog("");
//                new Login().getApplyExamtionthematiclear(userId, orgId, stId, this, 1);//申请考试
//            }
//        }else
        if (requestCode == 0) {
            if (resultCode == 1) {//100101、100102、100103两类管理员培训补全信息后直接申请考试
//                //检测是否有写的权限
//                SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
//                int stId = sp.getInt("stId", 0);
//                String orgId = sp.getString("orgId", "");
//                LoginUserBean userInfo = UserManger.getUserInfo();
//                LoginUserBean.DataBean databean = userInfo.getData();
//                String userId = databean.getUserId();
//                int permission = ActivityCompat.checkSelfPermission(getContext(),
//                        "android.permission.WRITE_EXTERNAL_STORAGE");
//                if (permission != PackageManager.PERMISSION_GRANTED) {
//                    // 没有写的权限，去申请写的权限，会弹出对话框
//                    ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
//                    return;
//                }
//                showLoadingDialog("");
//                new Login().getApplyExamtionthematiclear(userId, orgId, stId, this, 1);//申请考试
                ApplyExamtion();
            }
        }
    }

    @Override
    public void initData() {
        ptr_main = (PtrClassicFrameLayout)getActivity().findViewById(R.id.ptr_main);
        tv_exam_learning = (TextView) getActivity().findViewById(R.id.tv_exam_learning);
        tv_exam3 = (TextView)getActivity().findViewById(R.id.tv_exam3);
        re_test = (RelativeLayout)getActivity().findViewById(R.id.re_test);
        tv_exam4 = (TextView)getActivity().findViewById(R.id.tv_exam4);
        tv_test3 = (TextView) getActivity().findViewById(R.id.tv_test3);
        lv_exam = (LinearListView) getActivity().findViewById(R.id.lv_exam);

        tv_exam_learning.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isFastClicker()) {
                    return;
                }
                if (tv_exam_learning.getText().toString().trim().equals("查看结业证书")) {
                    SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                    String orgId = sp.getString("orgId", "");
                    String stName = sp.getString("stName", "");
                    int stId = sp.getInt("stId", 0);
                    int uschSn = sp.getInt("uschSn", 0);
                    if (stId == 500001)//500001继续教育
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("orgId", orgId);
                        bundle.putInt("stId", stId);
                        bundle.putInt("uschSn", uschSn);
                        startActivity(ContinuingEducationActivity.class, bundle);
                    } else if (stId == 100101 || stId == 100102 || stId == 100103)//两类管理员结业证书
                    {
                        if (stId == 100101) {
                            Bundle bundle = new Bundle();
                            bundle.putString("orgId", orgId);
                            bundle.putInt("stId", stId);
                            bundle.putInt("uschSn", uschSn);
                            startActivity(InitialposttrainingActivity.class, bundle);
                        } else if (stId == 100102 || stId == 100103)//通用结业证书
                        {
                            LoginUserBean userInfo = UserManger.getUserInfo();
                            LoginUserBean.DataBean databean = userInfo.getData();
                            String userId = databean.getUserId();
                            String certUrl = AppInterfaceConfig.BASE_URL + "app/spec/toSpecTCert?" + "userId=" + userId + "&orgId=" + orgId + "&stId=" + stId + "&usch=" + uschSn;
                            Bundle bundle = new Bundle();
                            bundle.putString("certUrl", certUrl);
                            startActivity(AdministratorcertificateActivity.class, bundle);
                        }
                    } else if (stId == 100001) {//2019从业人员专项培训结业证书
                        Bundle bundle = new Bundle();
                        bundle.putString("orgId", orgId);
                        bundle.putString("stName", stName);
                        bundle.putInt("stId", stId);
                        bundle.putInt("uschSn", uschSn);
                        startActivity(CertificateCompletionActivity.class, bundle);
                    } else {//通用结业证书
                        String certUrl = AppInterfaceConfig.BASE_URL + "app/spec/toSpecTCertNew?"+"uschSn=" + uschSn+"&uqpSn="+uqpSn;
                        Bundle bundle = new Bundle();
                        bundle.putString("certUrl", certUrl);
                        startActivity(AdministratorcertificateActivity.class, bundle);
                    }
                } else if (tv_exam_learning.getText().toString().trim().equals("我知道了，继续考试")) {
                    //检测是否有写的权限
                    int permission = ActivityCompat.checkSelfPermission(getContext(),
                            "android.permission.WRITE_EXTERNAL_STORAGE");
                    if (permission != PackageManager.PERMISSION_GRANTED) {
                        // 没有写的权限，去申请写的权限，会弹出对话框
                        ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                        return;
                    }
                    SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                    String orgId = sp.getString("orgId", "");
                    int apromptMark = sp.getInt("apromptMark", 0);
                    showLoadingDialog("");
                    Bundle bundle = new Bundle();
                    bundle.putInt("sn", newrows.get(0).getSn());
                    bundle.putString("orgId", orgId);
                    bundle.putInt("qpsn", newrows.get(0).getQpSn());
                    bundle.putInt("apromptMark", apromptMark);
                    startActivity(ExaminationthematiclearningActivity.class, bundle);

                } else if (tv_exam_learning.getText().toString().trim().equals("我知道了，申请考试"))//开始考试 申请考试
                {
                    SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                    int stId = sp.getInt("stId", 0);
                    String orgId = sp.getString("orgId", "");
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean databean = userInfo.getData();
                    String userId = databean.getUserId();
                    if (stId == 500001) {//校验继续教育是否可以考试
                        new Login().getcheckExamTime(userId, orgId, stId, (HttpListener) getContext(), 7);
                        return;
                    }
                    if (stId == 100101 || stId == 100102 || stId == 100103)//查询专项培训结业用户信息
                    {
                        new Login().getuserStCertfind(userId, orgId, stId, (HttpListener) getContext(), 8);
                        return;
                    }
                    ApplyExamtion();//申请考卷业务方法

                }
            }
        });

        //注册EventBus
        EventBus.getDefault().register(this);
        api = WXAPIFactory.createWXAPI(getActivity(), Constants.APP_ID);

        //下拉刷新
        final WindmillHeader header = new WindmillHeader(getActivity());
        final ImageLoadingListener listener = new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                ptr_main.refreshComplete();
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                ptr_main.refreshComplete();
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                ptr_main.refreshComplete();
            }
        };


        ptr_main.setHeaderView(header);
        ptr_main.addPtrUIHandler(header);
        //下拉刷新
        ptr_main.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initpredata();//刷新数据
                        ptrTimes++;
                        ptr_main.refreshComplete();
                    }
                }, 2000);
            }
        });


        lv_exam.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                if (Utils.isFastClicker()) {
                    return;
                }
                SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                String orgId = sp.getString("orgId", "");
                int apromptMark = sp.getInt("apromptMark", 0);
                int finishMark = examationAdapter.getItem(position).getFinishMark();
                if (finishMark == 1) {

                    Bundle bundle = new Bundle();
                    bundle.putInt("havesn", examationAdapter.getItem(position).getSn());
                    bundle.putLong("havecreation", examationAdapter.getItem(position).getCreationDate());
                    bundle.putInt("haveqpsn", examationAdapter.getItem(position).getQpSn());
                    bundle.putString("haveqptName", examationAdapter.getItem(position).getQptName());
                    bundle.putString("haveqpName", examationAdapter.getItem(position).getQpName());
                    bundle.putInt("havetotalScore", examationAdapter.getItem(position).getTotalScore());
                    bundle.putInt("havepassScore", examationAdapter.getItem(position).getPassScore());
                    bundle.putInt("havescore", examationAdapter.getItem(position).getScore());
                    bundle.putInt("havepassMark", examationAdapter.getItem(position).getPassMark());
                    bundle.putLong("testEndDate", examationAdapter.getItem(position).getTestEndDate());
                    bundle.putString("signPicUrl", examationAdapter.getItem(position).getSignPicUrl());

                    /**
                     * 此处要传这条已考的所有数据
                     */
                    startActivity(HaveExaminationthematiclearningActivity.class, bundle);
                } else {
                    //检测是否有写的权限
                    int permission = ActivityCompat.checkSelfPermission(getContext(),
                            "android.permission.WRITE_EXTERNAL_STORAGE");
                    if (permission != PackageManager.PERMISSION_GRANTED) {
                        // 没有写的权限，去申请写的权限，会弹出对话框
                        ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                        return;
                    }
                    showLoadingDialog("");
                    Bundle bundle = new Bundle();
                    bundle.putInt("sn", examationAdapter.getItem(position).getSn());
                    bundle.putString("orgId", orgId);
                    bundle.putInt("qpsn", examationAdapter.getItem(position).getQpSn());
                    bundle.putInt("apromptMark", apromptMark);

                    /**
                     * 此处要传这条待考的所有数据
                     */
                    startActivity(ExaminationthematiclearningActivity.class, bundle);

                }

            }
        });

    }

    //刷新数据
    private void initpredata() {
        SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        String rolename = sp.getString("rolename", "");
        String adId = sp.getString("adId", "");
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        getThematicLearnRecord();
        new Login().getUser(userId, this, 4);   //验证是否有身份证信息判断按钮是否为灰
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        String rolename = sp.getString("rolename", "");
        String adId = sp.getString("adId", "");
        // int stId = sp.getInt("stId", 0);
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        getThematicLearnRecord();
        new Login().getUser(userId, this, 4);   //验证是否有身份证信息判断按钮是否为灰
    }


    @Override
    public void requestData() {
        String orgId = getArguments().getString("orgId");
        String orgName = getArguments().getString("orgName");
        sn = getArguments().getInt("sn");
        int stId = getArguments().getInt("stId");
        String rolename = getArguments().getString("rolename");
        String adId = getArguments().getString("adId");
        int position = getArguments().getInt("position");
        int ihveMark = getArguments().getInt("ihveMark");

        SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putInt("stId", stId);
        edit.putInt("position", position);
        edit.putInt("ihveMark", ihveMark);
        edit.putString("orgId", orgId);
        edit.putString("orgName", orgName);
        edit.putString("rolename", rolename);
        edit.putString("adId", adId);
        edit.commit();
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();

        getThematicLearnRecord();
        new Login().getUser(userId, this, 4);   //验证是否有身份证信息判断按钮是否为灰


    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            dismissLoadingDialog();
            SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
            String orgId = sp.getString("orgId", "");
            int apromptMark = sp.getInt("apromptMark", 0);
            DaiKaoCourseBean daiKaoCourseBean = JSON.parseObject(result, DaiKaoCourseBean.class);
            DaiKaoCourseBean.DataBean databean = daiKaoCourseBean.getData();
            int qpSn = databean.getQpSn();
            int sn = databean.getSn();
            if (qpSn != 0) {
                Bundle bundle = new Bundle();
                bundle.putInt("sn", sn);
                bundle.putString("orgId", orgId);
                bundle.putInt("qpsn", qpSn);
                bundle.putInt("apromptMark", apromptMark);
                /**
                 * 此处要传这条待考的所有数据
                 */
                startActivity(ExaminationthematiclearningActivity.class, bundle);
            }
        } else if (what == 2) {
            dismissLoadingDialog();
            DaikaoBean daikaoBean = JSON.parseObject(result, DaikaoBean.class);
            List<DaikaoBean.RowsBean> daikaorows = daikaoBean.getRows();
            SharedPreferences sp = getContext().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
            int finishMark = sp.getInt("finishMark", 0);
            int onlyExamMark = sp.getInt("onlyExamMark", 0);
            if (finishMark == 0) {
                if (onlyExamMark == 0)//要学习完才能考试
                {
                    finishrows.clear();
                    if (daikaorows.size() == 0) {
                        tv_exam_learning.setEnabled(false);
                        tv_exam_learning.setBackgroundResource(R.drawable.notestbutton);//不可点击
                        re_test.setVisibility(View.GONE);
                        return;
                    }
                    for (int i = 0; i < daikaorows.size(); i++) {

                        if (daikaorows.get(i).getFinishMark() == 1) {
                            finishrows.add(daikaorows.get(i));
                        }
                    }
                    if (finishrows.size() == 0) {
                        tv_exam_learning.setEnabled(false);
                        tv_exam_learning.setBackgroundResource(R.drawable.notestbutton);//不可点击
                        re_test.setVisibility(View.GONE);
                        lv_exam.setAdapter(null);
                    } else if (finishrows.size() > 0) {
                        re_test.setVisibility(View.VISIBLE);
                        finishrowslist.clear();
                        for (int i = 0; i < finishrows.size(); i++) {
                            if (finishrows.get(i).getPassMark() == 1) {
                                finishrowslist.add(finishrows.get(i));
                            }
                        }
                        if (finishrowslist.size() > 0)//及格
                        {
                            tv_exam3.setVisibility(View.GONE);
                            Integer checkMark = finishrowslist.get(0).getCheckMark();
                            if (checkMark == 3) {
                                tv_exam_learning.setEnabled(true);
                                tv_exam_learning.setText("查看结业证书");
                                tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                            } else {
                                tv_exam_learning.setEnabled(false);
                                tv_exam_learning.setText("待审核");
                                tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);
                            }

                        } else if (finishrowslist.size() == 0) {
                            tv_exam3.setVisibility(View.VISIBLE);
                            tv_exam_learning.setEnabled(false);
                            tv_exam_learning.setBackgroundResource(R.drawable.notestbutton);//不可点击
                        }
                    }
                    examationAdapter = new ExamationAdapter(getContext(), finishrows, R.layout.testandexamiantion_item_layout2);
                    lv_exam.setAdapter(examationAdapter);
                } else if (onlyExamMark == 1)//直接考试
                {
                    finishrows.clear();
                    finishnorows.clear();
                    newrows.clear();
                    if (daikaorows.size() == 0) {
                        tv_exam_learning.setEnabled(true);
                        tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                        re_test.setVisibility(View.GONE);

                        return;
                    }
                    re_test.setVisibility(View.VISIBLE);
                    for (int i = 0; i < daikaorows.size(); i++) {

                        if (daikaorows.get(i).getFinishMark() == 1) {
                            finishrows.add(daikaorows.get(i));
                        } else {
                            finishnorows.add(daikaorows.get(i));
                        }
                    }
                    newrows.addAll(finishnorows);
                    newrows.addAll(finishrows);

                    if (finishnorows.size() >= 1) {//未完成记录>=1条判断
                        if (finishrows.size() >= 1) {
                            finishrowslist.clear();
                            for (int i = 0; i < finishrows.size(); i++) {
                                if (finishrows.get(i).getPassMark() == 1) {
                                    finishrowslist.add(finishrows.get(i));
                                }
                            }
                            if (finishrowslist.size() > 0)//及格
                            {
                                Integer checkMark = finishrowslist.get(0).getCheckMark();
//                                tv_exam_learning.setEnabled(true);
//                                tv_exam_learning.setText("查看结业证书");
//                                tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                                if (checkMark == 3) {
                                    tv_exam_learning.setEnabled(true);
                                    tv_exam_learning.setText("查看结业证书");
                                    tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                                } else {
                                    tv_exam_learning.setEnabled(false);
                                    tv_exam_learning.setText("待审核");
                                    tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);
                                }

                            } else if (finishrowslist.size() == 0)//不及格
                            {
                                tv_exam3.setVisibility(View.VISIBLE);
                                tv_exam3.setText("您考试还未合格，请继续考试！");
                                tv_exam_learning.setEnabled(true);
                                tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                                tv_exam_learning.setText("我知道了，继续考试");
                            }

                        } else if (finishrows.size() == 0) {
                            tv_exam_learning.setEnabled(true);
                            tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                            tv_exam_learning.setText("我知道了，继续考试");
                        }
                    } else if (finishnorows.size() == 0) {//未完成记录0条判断
                        finishrowslist.clear();
                        for (int i = 0; i < finishrows.size(); i++) {
                            if (finishrows.get(i).getPassMark() == 1) {
                                finishrowslist.add(finishrows.get(i));
                            }
                        }
                        if (finishrowslist.size() > 0)//及格
                        {
//                        int outSMark = finishrowslist.get(0).getOutSMark();
//                        String outSDesc = finishrowslist.get(0).getOutSDesc();
//                        if(outSMark==1)
//                        { //及格，提交成功给运管所
//                            tv_exam_learning.setEnabled(true);
//                            tv_exam_learning.setText("查看结业证书");
//                            tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
//                        }else {//及格，未提交或者提交失败给运管所
//                            tv_exam_learning.setEnabled(true);
//                            tv_exam_learning.setText("查看结业证书");
//                            tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
//                        }
                            Integer checkMark = finishrowslist.get(0).getCheckMark();
                            if (checkMark == 3) {
                                tv_exam_learning.setEnabled(true);
                                tv_exam_learning.setText("查看结业证书");
                                tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                            } else {
                                tv_exam_learning.setEnabled(false);
                                tv_exam_learning.setText("待审核");
                                tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);
                            }

                        } else if (finishrowslist.size() == 0)//不及格
                        {
                            tv_exam3.setVisibility(View.VISIBLE);
                            tv_exam3.setText("您考试还未合格，请继续考试！");
                            tv_exam_learning.setEnabled(true);
                            tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                            tv_exam_learning.setText("我知道了，申请考试");
                        }
                    }
                    examationAdapter = new ExamationAdapter(getContext(), newrows, R.layout.testandexamiantion_item_layout2);
                    lv_exam.setAdapter(examationAdapter);
                }
            } else if (finishMark == 1 || finishMark == 2) {

                finishrows.clear();
                finishnorows.clear();
                newrows.clear();
                if (daikaorows.size() == 0) {
                    tv_exam_learning.setEnabled(true);
                    tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                    re_test.setVisibility(View.GONE);
                    return;
                }
                re_test.setVisibility(View.VISIBLE);
                for (int i = 0; i < daikaorows.size(); i++) {
                    if (daikaorows.get(i).getFinishMark() == 1) {
                        finishrows.add(daikaorows.get(i));
                    } else {
                        finishnorows.add(daikaorows.get(i));
                    }
                }
                newrows.addAll(finishnorows);
                newrows.addAll(finishrows);

                if (finishnorows.size() >= 1) {//未完成记录>=1条判断
                    if (finishrows.size() >= 1) {
                        finishrowslist.clear();
                        for (int i = 0; i < finishrows.size(); i++) {
                            if (finishrows.get(i).getPassMark() == 1) {
                                finishrowslist.add(finishrows.get(i));
                            }
                        }
                        if (finishrowslist.size() > 0)//及格
                        {
//                         int outSMark = finishrowslist.get(0).getOutSMark();
//                         String outSDesc = finishrowslist.get(0).getOutSDesc();
//                         if(outSMark==1)
//                         {//及格，提交成功给运管所
//                             tv_exam_learning.setEnabled(true);
//                             tv_exam_learning.setText("查看结业证书");
//                             tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
//                         }else {//及格，未提交或者提交失败给运管所
//                             tv_exam_learning.setEnabled(true);
//                             tv_exam_learning.setText("查看结业证书");
//                             tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
//                         }
                            Integer checkMark = finishrowslist.get(0).getCheckMark();
                            if (checkMark == 3) {
                                tv_exam_learning.setEnabled(true);
                                tv_exam_learning.setText("查看结业证书");
                                tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                            } else {
                                tv_exam_learning.setEnabled(false);
                                tv_exam_learning.setText("待审核");
                                tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);
                            }
                        } else if (finishrowslist.size() == 0)//不及格
                        {
                            tv_exam3.setVisibility(View.VISIBLE);
                            tv_exam3.setText("您考试还未合格，请继续考试！");
                            tv_exam_learning.setEnabled(true);
                            tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                            tv_exam_learning.setText("我知道了，继续考试");
                        }

                    } else if (finishrows.size() == 0) {
                        tv_exam_learning.setEnabled(true);
                        tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                        tv_exam_learning.setText("我知道了，继续考试");
                    }
                } else if (finishnorows.size() == 0) {//未完成记录0条判断
                    finishrowslist.clear();
                    for (int i = 0; i < finishrows.size(); i++) {
                        if (finishrows.get(i).getPassMark() == 1) {
                            finishrowslist.add(finishrows.get(i));
                        }
                    }
                    if (finishrowslist.size() > 0)//及格
                    {
                        Integer checkMark = finishrowslist.get(0).getCheckMark();
                        if (checkMark == 3) {
                            tv_exam_learning.setEnabled(true);
                            tv_exam_learning.setText("查看结业证书");
                            tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                        } else {
                            tv_exam_learning.setEnabled(false);
                            tv_exam_learning.setText("待审核");
                            tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);
                        }
                    } else if (finishrowslist.size() == 0)//不及格
                    {
                        tv_exam3.setVisibility(View.VISIBLE);
                        tv_exam3.setText("您考试还未合格，请继续考试！");
                        tv_exam_learning.setEnabled(true);
                        tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                        tv_exam_learning.setText("我知道了，申请考试");
                    }
                }
                examationAdapter = new ExamationAdapter(getContext(), newrows, R.layout.testandexamiantion_item_layout2);
                lv_exam.setAdapter(examationAdapter);
            }

            if(!tv_exam_learning.getText().toString().equals("查看结业证书")){
                tv_exam_learning.setVisibility(View.GONE);
            }else{
                uqpSn=finishrowslist.get(0).getUqpSn();
            }
        } else if (what == 3) {
            /*SpecifiedLearnAllBean specifiedLearnAllBean = JSON.parseObject(result, SpecifiedLearnAllBean.class);
            List<SpecifiedLearnAllBean.RowsBean> rows = specifiedLearnAllBean.getRows();
            for (int i = 0; i < rows.size(); i++) {
                if (rows.get(i).getShowTrml() != 3) {
                    jiayunbaoSpecified.add(rows.get(i));
                }
            }
            SharedPreferences sp = getContext().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
            int position = sp.getInt("position", 0);
            Integer finishMark = jiayunbaoSpecified.get(position).getFinishMark();
            Integer payMark = jiayunbaoSpecified.get(position).getPayMark();
            String stName = jiayunbaoSpecified.get(position).getStName();
            float price = jiayunbaoSpecified.get(position).getPrice();
            Integer chargeMark = jiayunbaoSpecified.get(position).getChargeMark();
            Integer onlyExamMark = jiayunbaoSpecified.get(position).getOnlyExamMark();
            Integer apromptMark = jiayunbaoSpecified.get(position).getApromptMark();
            Integer uschSn = jiayunbaoSpecified.get(position).getUschSn();
            String twoDecimal = getTwoDecimal(price);
            Integer defExamNo = jiayunbaoSpecified.get(position).getDefExamNo();
            float oneExamPrice = jiayunbaoSpecified.get(position).getOneExamPrice();

            Integer thematicFaceRecgMark = jiayunbaoSpecified.get(position).getFaceRecgMark();
            SharePerferenceUtils.putInt(getContext(), "thematicFaceRecgMark", thematicFaceRecgMark);

            SharedPreferences.Editor edit = sp.edit();
            edit.putString("twoDecimal", twoDecimal);
            edit.putString("stName", stName);
            edit.putInt("payMark", payMark);
            edit.putInt("apromptMark", apromptMark);
            edit.putInt("chargeMark", chargeMark);
            edit.putInt("finishMark", finishMark);
            edit.putInt("onlyExamMark", onlyExamMark);
            edit.putInt("uschSn", uschSn);
            edit.putInt("defExamNo", defExamNo);
            edit.putFloat("oneExamPrice", oneExamPrice);
            edit.commit();
            if (finishMark == 1 || finishMark == 2)//学习完成考试
            {
                tv_exam3.setVisibility(View.GONE);
                String orgId = sp.getString("orgId", "");
                int stId = sp.getInt("stId", 0);
                LoginUserBean userInfo = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo.getData();
                String userId = data.getUserId();
                showLoadingDialog("");
                new Login().getTestandexamination(userId, orgId, stId, 0, null,this, 2);
            } else if (finishMark == 0) {
                if (onlyExamMark == 0) {//要学习完才能考试
                    tv_exam3.setVisibility(View.VISIBLE);
                    tv_exam_learning.setEnabled(false);
                    tv_exam_learning.setBackgroundResource(R.drawable.notestbutton);//不可点击
                    String orgId = sp.getString("orgId", "");
                    int stId = sp.getInt("stId", 0);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean data = userInfo.getData();
                    String userId = data.getUserId();
                    showLoadingDialog("");
                    new Login().getTestandexamination(userId, orgId, stId, 0, null,this, 2);

                } else if (onlyExamMark == 1)//直接考试
                {
                    tv_exam3.setVisibility(View.GONE);
                    tv_exam_learning.setEnabled(true);
                    tv_exam_learning.setBackgroundResource(R.drawable.shape_home_selector);//可点击
                    String orgId = sp.getString("orgId", "");
                    int stId = sp.getInt("stId", 0);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean data = userInfo.getData();
                    String userId = data.getUserId();
                    showLoadingDialog("");
                    new Login().getTestandexamination(userId, orgId, stId, 0, null,this, 2);
                }
            }*/
        } else if (what == 4) {

            MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
            MineUseBean.DataBean data = mineUseBean.getData();
            String idcNo = data.getIdcNo();
            //       String bcNo = data.getBcNo();
            if (idcNo == null) {
                SharedPreferences sp = getContext().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("idcNo", "");
                edit.commit();
            } else {
                SharedPreferences sp = getContext().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("idcNo", idcNo);
                edit.commit();
            }
        } else if (what == THEMATIC_LEARNRECORD_DATA) {
            ThematicLearnRecordBean bean = JSON.parseObject(result, ThematicLearnRecordBean.class);
            List<ThematicLearnRecordBean.RowsBean> rowsBeans = bean.getRows();

            SharedPreferences sp = getContext().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
            int position = sp.getInt("position", 0);
            Integer finishMark = rowsBeans.get(position).getFinishMark();
            Integer payMark = rowsBeans.get(position).getPayMark();
            String stName = rowsBeans.get(position).getStName();
            /*float price = rowsBeans.get(position).getPrice();
            Integer chargeMark = rowsBeans.get(position).getChargeMark();
            Integer onlyExamMark = rowsBeans.get(position).getOnlyExamMark();
            Integer apromptMark = rowsBeans.get(position).getApromptMark();
            Integer uschSn = rowsBeans.get(position).getUschSn();
            String twoDecimal = getTwoDecimal(price);
            Integer defExamNo = rowsBeans.get(position).getDefExamNo();
            float oneExamPrice = rowsBeans.get(position).getOneExamPrice();

            Integer thematicFaceRecgMark = rowsBeans.get(position).getFaceRecgMark();*/
            /*SharePerferenceUtils.putInt(getContext(), "thematicFaceRecgMark", thematicFaceRecgMark);

            SharedPreferences.Editor edit = sp.edit();
            edit.putString("twoDecimal", twoDecimal);
            edit.putString("stName", stName);
            edit.putInt("payMark", payMark);
            edit.putInt("apromptMark", apromptMark);
            edit.putInt("chargeMark", chargeMark);
            edit.putInt("finishMark", finishMark);
            edit.putInt("onlyExamMark", onlyExamMark);
            edit.putInt("uschSn", uschSn);
            edit.putInt("defExamNo", defExamNo);
            edit.putFloat("oneExamPrice", oneExamPrice);
            edit.commit();*/
            if (finishMark == 1 || finishMark == 2)//学习完成考试
            {
                tv_exam3.setVisibility(View.GONE);
                String orgId = sp.getString("orgId", "");
                int stId = sp.getInt("stId", 0);
                LoginUserBean userInfo = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo.getData();
                String userId = data.getUserId();
                showLoadingDialog("");
                new Login().getTestandexamination(userId, orgId, stId, 0, sn + "", this, 2);
            }
        }
//        else if(what==5)
//        {
//           dismissLoadingDialog();
//            showToast("保存成功");
//            mUserPopWindow.dismiss();
//            LoginUserBean userInfo = UserManger.getUserInfo();
//            LoginUserBean.DataBean data = userInfo.getData();
//            String userId = data.getUserId();
//            new Login().getUser(userId,this,4);   //再次验证是否有身份证信息判断按钮是否为灰
//        }
//        else if(what==6)
//        {
//            dismissLoadingDialog();
//            showToast("保存成功");
//            mUserihvePopWindow.dismiss();
//            LoginUserBean userInfo = UserManger.getUserInfo();
//            LoginUserBean.DataBean data = userInfo.getData();
//            String userId = data.getUserId();
//            new Login().getUser(userId,this,4);   //再次验证是否有经营许可证号信息判断按钮是否为灰
//        }
        else if (what == 7) {
            CheckExamtimeBean checkExamtimeBean = JSON.parseObject(result, CheckExamtimeBean.class);
            CheckExamtimeBean.DataBean dataBean = checkExamtimeBean.getData();
            int allowMark = dataBean.getAllowMark();
            int min = dataBean.getMin();//剩余分钟数
            int secondtime = min * 60;
            String onlyTime = getStringTime(secondtime);
            if (allowMark == 0) {

                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getActivity());
                builder1.setMessage("还需要 " + onlyTime + " 才能申请考试");
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
                builder1.create().show();
                return;
            }
            ApplyExamtion();
        } else if (what == 8) {
            CheckExamtimeBean checkExamtimeBean = JSON.parseObject(result, CheckExamtimeBean.class);
            CheckExamtimeBean.DataBean dataBean = checkExamtimeBean.getData();
            String orgName = dataBean.getOrgName();
            String userName = dataBean.getUserName();
            //String userMobile = dataBean.getUserMobile();
            String idcNo = dataBean.getIdcNo();
            String address = dataBean.getAddress();
            String userPost = dataBean.getUserPost();
            SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
            String orgId = sp.getString("orgId", "");
            int stId = sp.getInt("stId", 0);
            int defExamNo = sp.getInt("defExamNo", 0);
            float oneExamPrice = sp.getFloat("oneExamPrice", 0);
            if (orgName == null || userName == null || idcNo == null || address == null || userPost == null) {
                Bundle bundle = new Bundle();
                bundle.putString("orgId", orgId);
                bundle.putInt("stId", stId);
                startActivityForResult(AdministratorInformationcompletionActivity.class, bundle, 0);
                return;
            }
            finishrowsfaillist.clear();
            for (int i = 0; i < finishrows.size(); i++) {
                if (finishrows.get(i).getPassMark() != 1) {
                    finishrowsfaillist.add(finishrows.get(i));
                }
            }
            if (finishrowsfaillist.size() >= defExamNo && oneExamPrice > 0) {
                showpurchasepopwindow(oneExamPrice);//考试次数不足继续购买
                return;
            }

            ApplyExamtion();
        } else if (what == 9) {
            PayMentSencondBean payMentBean = JSON.parseObject(result, PayMentSencondBean.class);
            String msg = payMentBean.getMsg();//支付订单系列号
            SharedPreferences sp1 = getActivity().getSharedPreferences("msg", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit1 = sp1.edit();
            edit1.putString("msg", msg);
            edit1.putInt("paytag", 8);
            edit1.commit();
            PayMentSencondBean.DataBean paydata = payMentBean.getData();//微信服务器返回的结果
            if (paydata != null) {
                api.registerApp(Constants.APP_ID);
                PayReq req = new PayReq();
                req.appId = Constants.APP_ID;
                req.packageValue = "Sign=WXPay";
                req.partnerId = paydata.getPartnerid();
                req.prepayId = paydata.getPrepayid();
                req.nonceStr = paydata.getNoncestr();
                req.timeStamp = paydata.getTimestamp();
                req.sign = paydata.getSign();
                api.sendReq(req);
            }
        }
        super.onSuccess(result, call, response, what);
    }

    private void showpurchasepopwindow(float oneExamPrice) {
        String oneExamPricestr = getTwoDecimal(oneExamPrice);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.purchase_popwindowlayout, null);
        mPurchasePopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        final LinearLayout le_takepicture = (LinearLayout) contentView.findViewById(R.id.le_takepicture);//跟布局
        TextView tv_price = (TextView) contentView.findViewById(R.id.tv_photo8);
        tv_price.setText("如需继续补考，请先购买单次考试费用，是否支付 ¥ " + oneExamPricestr + "?");
        TextView img_sure = (TextView) contentView.findViewById(R.id.img_photo1);//确定
        TextView img_no = (TextView) contentView.findViewById(R.id.img_photo2);//取消
        mPurchasePopWindow.setFocusable(false);
        mPurchasePopWindow.setOutsideTouchable(false);
        mPurchasePopWindow.showAtLocation(le_takepicture, Gravity.CENTER, 0, 0);
        img_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPurchasePopWindow.dismiss();
                SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                String orgId = sp.getString("orgId", "");
                int stId = sp.getInt("stId", 0);
                LoginUserBean userInfo = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo.getData();
                String userId = data.getUserId();
                String phoneSign = getPhoneSign();//设备的唯一标识
                initpayment(userId, orgId, stId, oneExamPrice, phoneSign);//微信支付

            }
        });
        img_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPurchasePopWindow.dismiss();

            }
        });
    }

    private void initpayment(String userId, String orgId, int stId, float oneExamPrice, String phoneSign) {
        showToast("获取订单中...");
        new Login().getUserBuyStQp(userId, orgId, 2, stId, "APP", oneExamPrice, phoneSign, Constants.APP_ID, this, 9);

    }

    private String getStringTime(int cnt) {
        int hour = cnt / 3600;
        int min = cnt % 3600 / 60;
        //int second = cnt % 60;
        return String.format(Locale.CHINA, "%02d小时%02d分", hour, min);
    }
//    private void showpopwindow() {
//
//        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.checkuser_popwindowlayout, null);
//        mUserPopWindow = new PopupWindow(contentView,
//                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
//        ed_id = (EditText) contentView.findViewById(R.id.ed_id);
//        mUserPopWindow.showAtLocation(ed_id, Gravity.CENTER, 0, 0);
//        // 编辑框设置触摸监听
//        ed_id.setOnTouchListener(new View.OnTouchListener() {
//
//            @SuppressLint("ClickableViewAccessibility")
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (MotionEvent.ACTION_DOWN == event.getAction()) {
//                    ed_id.setCursorVisible(true);// 再次点击显示光标
//                }
//                return false;
//            }
//        });
//        TextView tv_idsave = (TextView) contentView.findViewById(R.id.tv_idsave);
//        tv_idsave.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//               // mUserPopWindow.dismiss();
//                String id = ed_id.getText().toString().trim();
//                 if(id.equals(""))
//                 {
//                    showToast("身份证不为空");
//                    return;
//                 }
//                    if (!IsIDcard(id)) {
//                        showToast("身份证无效");
//                        return;
//                    }
//                LoginUserBean userInfo1 = UserManger.getUserInfo();
//                LoginUserBean.DataBean data = userInfo1.getData();
//                String userId = data.getUserId();
//                ImputUserID(userId,id);
//
//            }
//        });
//
//    }
//    private void showihvepopwindow() {
//
//        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.checkiver_popwindowlayout, null);
//        mUserihvePopWindow = new PopupWindow(contentView,
//                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
//        ed_idiver = (EditText) contentView.findViewById(R.id.ed_idiver);
//        mUserihvePopWindow.showAtLocation(ed_idiver, Gravity.CENTER, 0, 0);
//// 编辑框设置触摸监听
//        ed_idiver.setOnTouchListener(new View.OnTouchListener() {
//
//            @SuppressLint("ClickableViewAccessibility")
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (MotionEvent.ACTION_DOWN == event.getAction()) {
//                    ed_idiver.setCursorVisible(true);// 再次点击显示光标
//                }
//                return false;
//            }
//        });
//        TextView tv_idsave = (TextView) contentView.findViewById(R.id.tv_idsave);
//        tv_idsave.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String iver = ed_idiver.getText().toString().trim();
//                if(iver.equals(""))//不输入经营许可证申请考卷
//                {
//                    mUserihvePopWindow.dismiss();
//                    SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
//                    String orgId = sp.getString("orgId", "");
//                    int stId = sp.getInt("stId", 0);
//                    LoginUserBean userInfo = UserManger.getUserInfo();
//                    LoginUserBean.DataBean databean = userInfo.getData();
//                    String userId = databean.getUserId();
//                    String twoDecimal = sp.getString("twoDecimal", "");
//                    String stName = sp.getString("stName", "");
//                    float newrice = Float.parseFloat(twoDecimal);
//                    int payMark = sp.getInt("payMark", 0);
//                    int chargeMark = sp.getInt("chargeMark", 0);
//                    if (chargeMark == 1 || chargeMark == 2) {
//                        //检测是否有写的权限
//                        int permission = ActivityCompat.checkSelfPermission(getContext(),
//                                "android.permission.WRITE_EXTERNAL_STORAGE");
//                        if (permission != PackageManager.PERMISSION_GRANTED) {
//                            // 没有写的权限，去申请写的权限，会弹出对话框
//                            ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
//                            return;
//                        }
//                        initApplyExamtion(userId,orgId,stId);
//
//                    } else if (chargeMark == 3) {
//                        if (payMark == 2||payMark == 1) {//2付费 1 免费
//                            //检测是否有写的权限
//                            int permission = ActivityCompat.checkSelfPermission(getContext(),
//                                    "android.permission.WRITE_EXTERNAL_STORAGE");
//                            if (permission != PackageManager.PERMISSION_GRANTED) {
//                                // 没有写的权限，去申请写的权限，会弹出对话框
//                                ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
//                                return;
//                            }
//                            initApplyExamtion(userId,orgId,stId);
//                        } else if(payMark == 0){//待支付
//                            Bundle bundle = new Bundle();
//                            bundle.putString("orgId", orgId);
//                            bundle.putInt("stId", stId);
//                            bundle.putInt("paytag", 3);
//                            bundle.putFloat("price", newrice);
//                            bundle.putString("stName", stName);
//                            startActivity(NewPaymentActivity.class, bundle);
//                        }
//                    }
//                }else {//输入经营许可证申请考卷
//
//                    LoginUserBean userInfo1 = UserManger.getUserInfo();
//                    LoginUserBean.DataBean data = userInfo1.getData();
//                    String userId = data.getUserId();
//                    ImputUseriver(userId, iver);
//                }
//            }
//        });
//
//    }

//    private void ImputUseriver(String userId, String iver) {
//        showLoadingDialog("");
//        new Login().getImputUserBcNo(userId, iver,this,6);
//    }

//    private void ImputUserID(String userId, String id) {
//        showLoadingDialog("");
//        new Login().getImputUserID(userId, id,this,5);
//
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        if (event.getType() == MessageEvent.TYPE_14) {
            SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
            String stName = sp.getString("stName", "");
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
            builder1.setMessage("你已成功购买 " + "[专题学习]" + stName + "。");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                    String orgId = sp.getString("orgId", "");
                    int stId = sp.getInt("stId", 0);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean databean = userInfo.getData();
                    String userId = databean.getUserId();
                    //检测是否有写的权限
                    int permission = ActivityCompat.checkSelfPermission(getContext(),
                            "android.permission.WRITE_EXTERNAL_STORAGE");
                    if (permission != PackageManager.PERMISSION_GRANTED) {
                        // 没有写的权限，去申请写的权限，会弹出对话框
                        ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                        return;
                    }
                    initApplyExamtion(userId, orgId, stId);

                }
            });

            builder1.create().show();

        }
        if (event.getType() == MessageEvent.TYPE_16)//专项考试购买次数返回成功
        {
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
            builder1.setMessage("你已成功购买");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
//                    SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
//                    String orgId = sp.getString("orgId", "");
//                    int stId = sp.getInt("stId", 0);
//                    LoginUserBean userInfo = UserManger.getUserInfo();
//                    LoginUserBean.DataBean databean = userInfo.getData();
//                    String userId = databean.getUserId();
//                    //检测是否有写的权限
//                    int permission = ActivityCompat.checkSelfPermission(getContext(),
//                            "android.permission.WRITE_EXTERNAL_STORAGE");
//                    if (permission != PackageManager.PERMISSION_GRANTED) {
//                        // 没有写的权限，去申请写的权限，会弹出对话框
//                        ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
//                        return;
//                    }
//                    initApplyExamtion(userId,orgId,stId);

                }
            });

            builder1.create().show();

        } else if (event.getType() == MessageEvent.TYPE_3) {
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
            builder1.setMessage("你购买失败");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                }
            });

            builder1.create().show();
        } else if (event.getType() == MessageEvent.TYPE_17)//专项考试购买次数返回失败
        {
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
            builder1.setMessage("你购买失败");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                }
            });

            builder1.create().show();
        }
    }

    private void initApplyExamtion(String userId, String orgId, int stId) {
        showLoadingDialog("");
        new Login().getApplyExamtionthematiclear(userId, orgId, stId, this, 1);//申请考试
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        super.onError(result, call, response, what);
        if (what == 1) {
            dismissLoadingDialog();
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            int code = checkBean.getCode();
            if (code == 1880) {
                tv_exam_learning.setEnabled(false);
                tv_exam_learning.setBackgroundResource(R.drawable.notestbutton);//不可点击
            } else {
                String msg = checkBean.getMsg();
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
                builder1.setMessage(msg);
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ;
                        //设置你的操作事项
                    }
                });
                builder1.create().show();
            }
        } else if (what == 7) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                    //设置你的操作事项
                }
            });
            builder1.create().show();


        } else if (what == 8) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            if (code == 9004)//管理员信息未查询到数据
            {
                SharedPreferences sp = getActivity().getSharedPreferences("ExaminationthematiclearningFragment", Context.MODE_PRIVATE);
                String orgId = sp.getString("orgId", "");
                int stId = sp.getInt("stId", 0);
                Bundle bundle = new Bundle();
                bundle.putString("orgId", orgId);
                bundle.putInt("stId", stId);
                startActivityForResult(AdministratorInformationcompletionActivity.class, bundle, 0);
            } else {
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getActivity());
                builder1.setMessage(msg);
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ;
                        //设置你的操作事项
                    }
                });
                builder1.create().show();
            }

        } else if (what == 9)//支付ERROR
        {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getActivity());
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                    //设置你的操作事项
                }
            });
            builder1.create().show();
        }
    }

    /**
     * 将数据保留两位小数
     */
    private String getTwoDecimal(double num) {
        DecimalFormat dFormat = new DecimalFormat("#0.00");
        String yearString = dFormat.format(num);
        return yearString;
    }

    @Override
    public void onUserVisible() {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }

    public class ExamationAdapter extends CommonAdapter<DaikaoBean.RowsBean> {
        private Context context;
        private List<DaikaoBean.RowsBean> mList;

        public ExamationAdapter(Context context, List<DaikaoBean.RowsBean> mList, int itemLayoutId) {
            super(context, mList, itemLayoutId);
            this.context = context;
            this.mList = mList;
        }

        @Override
        public void convert(ViewHolder holder, DaikaoBean.RowsBean item, int positon) {
            //   TextView tv_testtitle = holder.getView(R.id.tv_testtitle);//日期
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_scon = holder.getView(R.id.tv_scon1);
            TextView tv_jige = holder.getView(R.id.tv_scon2);
            TextView tv_sign = holder.getView(R.id.tv_sign);
//
//           if(mList.get(0).getQpName()==null)
//           {
//               tv_test3.setText("");
//           }else{
//
//               tv_test3.setText(mList.get(0).getQpName());
//           }
            int finishMark = mList.get(positon).getFinishMark();
            if (finishMark == 1) {
                long creationDate = mList.get(positon).getCreationDate();
                //mill为你龙类型的时间戳
                if (creationDate > 0) {

                    Date date = new Date(creationDate);
                    String time = "";
                    try {
                        //yyyy表示年MM表示月dd表示日
                        //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        //进行格式化
                        time = sdf.format(date);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    tv_time.setText("考试时间 : " + time);
                }
                int score = mList.get(positon).getScore();
                tv_scon.setText(score + "分");
                tv_scon.setTextColor(getResources().getColor(R.color.hidetroublenext));
                tv_jige.setVisibility(View.VISIBLE);
                int passMark = mList.get(positon).getPassMark();
                if (passMark == 1) {
                    tv_jige.setText("及格");
                    tv_jige.setTextColor(getResources().getColor(R.color.hiddengreen));
                    tv_sign.setVisibility(View.VISIBLE);
                } else {
                    tv_jige.setText("不及格");
                    tv_jige.setTextColor(getResources().getColor(R.color.bixue_red));
                    tv_sign.setVisibility(View.GONE);
                }
            } else {
                tv_time.setText("考试时间 :");
                tv_scon.setText("未完成考试");
                tv_scon.setTextColor(getResources().getColor(R.color.holetotal_red));
                tv_jige.setVisibility(View.GONE);
                tv_sign.setVisibility(View.GONE);
            }

            final int sn = mList.get(positon).getSn();
            final String signPicUrl = mList.get(positon).getSignPicUrl();

            tv_sign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Bundle bundle = new Bundle();
                    bundle.putInt("sn", sn);
                    bundle.putString("signPicUrl", signPicUrl);
                    startActivity(SignExaminationthematiclearningActivity.class, bundle);

                }
            });
        }


    }

    //获取手机的唯一标识
    @SuppressLint("MissingPermission")
    public String getPhoneSign() {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
            // IMEI（imei）
            TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (!TextUtils.isEmpty(imei)) {
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!TextUtils.isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID();
            if (!TextUtils.isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID());
        }
        return deviceId.toString();
    }

    /**
     * 得到全局唯一UUID
     */
    private String uuid;

    public String getUUID() {
        SharedPreferences mShare = getActivity().getSharedPreferences("uuid", Context.MODE_PRIVATE);
        if (mShare != null) {
            uuid = mShare.getString("uuid", "");
        }
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString();
            mShare.edit().putString("uuid", uuid).commit();
        }
        return uuid;
    }


    private void getThematicLearnRecord() {//获取专题学习记录
        LoginUserBean userInfo = UserManger.getUserInfo();
        String userId = userInfo.getData().getUserId();
        new Course().findByCond(userId, 12, this, THEMATIC_LEARNRECORD_DATA);
    }
}
